//
//  MoreViewController.m
//  DaDaBao
//
//  Created by User on 15/8/12.
//  Copyright (c) 2015年 User. All rights reserved.
//

#import "OwnerViewController.h"

#import "OrderViewController.h"
#import "ChangePwdViewController.h"
#import "FeedbackViewController.h"
#import "LoginViewController.h"

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define iOS8 SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")
@interface OwnerViewController ()<UITableViewDataSource,UITableViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIAlertViewDelegate>

@property(nonatomic,strong)UITableView  *tableView;
@property(nonatomic,strong)UIView       *bgView;
@property(nonatomic,strong)UIView       *exitView;
@property(nonatomic,strong)UIButton     *headBtn;
@property(nonatomic,strong)NSArray      *dataArray1;
@property(nonatomic,strong)NSArray      *dataArray2;
@property(nonatomic,strong)UILabel      *nameLab;
@property (strong, nonatomic)UIView     *backColorView;
@property(strong,nonatomic)UIButton     *loginBtn;

@end

@implementation OwnerViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloginView) name:@"reLogin" object:nil];

    if ([AccountTools isLogin] == TRUE) {
        self.exitView.hidden = FALSE;
        self.loginBtn.hidden = TRUE;
        self.nameLab.hidden = FALSE;
    }
    else
    {
        self.exitView.hidden = TRUE;
        self.loginBtn.hidden = FALSE;
        self.nameLab.hidden = TRUE;
    }

//    [self.headBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",Index_Url_Test,[[NSUserDefaults standardUserDefaults]objectForKey:@"userHeadPhoto"]]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"img_default_head"]];
    NSString *phoneNum = [self secureThePhoneNum:[[NSUserDefaults standardUserDefaults]objectForKey:@"userCd"]];
    self.nameLab.text = [NSString stringWithFormat:@"HI,%@",phoneNum];
}

#pragma mark -  actionSheet
//- (void)headBtnAction
//{
//    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"上传头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相册",@"拍照", nil];
//    [actionSheet showInView:self.view];
//}
//
//- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
//    if (buttonIndex == 0) {
//        
//        //相册
//        [self showTheImagePickerController:1];
//        
//        
//    }else if(buttonIndex == 1){
//        //拍照
//        [self showTheImagePickerController:2];
//        
//    }else{
//        //取消
//    }
//}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self createSubViews];
    self.view.backgroundColor = [UIColor hexStringToColor:@"#f3f3f3"];

    
    
//    if (!_dataArray1) {
//        _dataArray1 = @[@"订单记录"];
//    }
//    if (!_dataArray2) {
////        _dataArray2 = @[@"资料修改",@"修改密码",@"意见反馈"];
//         _dataArray2 = @[@"修改密码",@"意见反馈"];
//    }
    if (!_dataArray1) {
        _dataArray1 = @[@"订单记录",@"修改密码",@"意见反馈"];
    }
    
}
#pragma mark-创建视图
-(void)createSubViews
{
    //    自定义navgationBar
    TopView *topView = [[TopView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_HEIGHT, 64.0f)];
    topView.backgroundColor = [UIColor hexStringToColor:COLOR_VALUE];
    [topView setTitile:@"我的账户"];
    [self.view addSubview:topView];
    
    //    建表
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, topView.frame.origin.y+topView.frame.size.height, SCREEN_WIDTH, SCREEN_HEIGHT - 64.0f - 49.0f) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorColor = UITableViewCellSelectionStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableHeaderView = self.bgView;
        _tableView.tableFooterView = self.exitView;
        
        
        
        [self.view addSubview:_tableView];
    }
    
}
-(UIView *)bgView
{
    if (!_bgView) {
        _bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,SCREEN_WIDTH , 150.0f) ];
        _bgView.backgroundColor = [UIColor hexStringToColor:COLOR_VALUE];
        [_bgView addSubview:self.headBtn];
        _nameLab = [[UILabel alloc] initWithFrame:CGRectMake(self.headBtn.frame.size.width+50.0f+20.0f, self.headBtn.frame.origin.y+self.headBtn.frame.size.height/2-20.0f, SCREEN_WIDTH-70.0f-self.headBtn.frame.size.width, 40.0f)];
        _nameLab.textAlignment = NSTextAlignmentLeft;
        _nameLab.text  = @"我是谁";
        
        _nameLab.font = [UIFont systemFontOfSize:20.0f];
        _nameLab.textColor = [UIColor whiteColor];
        _nameLab.hidden = TRUE;

        [_bgView addSubview:self.loginBtn];
        [_bgView addSubview:_nameLab];


    }
    return  _bgView;
    

}
-(UIButton *)headBtn
{
    if (!_headBtn) {
        _headBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _headBtn.frame = CGRectMake(50.0f, 32.0f, 66.0f, 66.0f);
        _headBtn.layer.cornerRadius =self.headBtn.bounds.size.width/2.0;
        [_headBtn setImage:[UIImage imageNamed:@"icon_myaccount"] forState:UIControlStateNormal];
        _headBtn.layer.masksToBounds = YES;
//        _headBtn.enabled = FALSE;
//        _headBtn.enabled = FALSE;
//        [_headBtn addTarget:self action:@selector(headBtnAction) forControlEvents:UIControlEventTouchUpInside];

    }
    return _headBtn;
}
-(UIView *)exitView
{
    if (!_exitView) {
        _exitView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 64.0f)];
      
        UIButton *exitBtn = [[UIButton alloc] initWithFrame:CGRectMake(16.0f,20.0f, SCREEN_WIDTH-32.0f, 44.0f)];
        [exitBtn addTarget:self action:@selector(exitButtonTapped) forControlEvents:UIControlEventTouchUpInside];
        [exitBtn setTitle:@"退出登录" forState:UIControlStateNormal];
        exitBtn.layer.cornerRadius = 2;
        [exitBtn setBackgroundColor:[UIColor hexStringToColor:COLOR_VALUE] forState:UIControlStateNormal];
        [_exitView addSubview:exitBtn];
        _exitView.hidden = TRUE;
    }
    
    return _exitView;
 
}
-(UIButton *)loginBtn
{
    if (!_loginBtn) {
        _loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _loginBtn.frame = CGRectMake(self.headBtn.frame.size.width+50.0f+20.0f, self.headBtn.frame.origin.y+self.headBtn.frame.size.height/2-20.0f, 100.0f, 40.0f);
        [_loginBtn setTitle:@"登录/注册" forState:UIControlStateNormal];
        [_loginBtn addTarget:self action:@selector(gotoLogin) forControlEvents:UIControlEventTouchUpInside];
        _loginBtn.hidden = TRUE;
        _loginBtn.layer.borderWidth = 1.0f;
        _loginBtn.layer.borderColor = [[UIColor whiteColor] CGColor];
    }
    return _loginBtn;
}
#pragma mark- 登陆按钮
-(void)gotoLogin
{
    LoginViewController *login = [[LoginViewController alloc] init];
    login.comeFromType = 1;
    [self presentViewController:login animated:TRUE completion:^{
        
    }];

}
#pragma mark- 退出按钮
-(void)exitButtonTapped
{
    [AccountTools exitLogin];
    [self gotoLogin];
}

#pragma mark- tableViewDatasource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        UILabel *sepLab = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 44.0f, SCREEN_WIDTH, 0.1f)];
        sepLab.backgroundColor = [UIColor blackColor];
        [cell addSubview:sepLab];
        
        
    }
    NSArray *arr = @[@"icon_myrecord",@"icon_password",@"icon_suggestion"];
    cell.imageView.image = [UIImage imageNamed:[arr objectAtIndex:indexPath.row]];
    cell.textLabel.text = [_dataArray1 objectAtIndex:indexPath.row];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    if (section==0) {
//        return _dataArray1.count;
//        
//    }
//    else
//    {
//        return _dataArray2.count;
//    }
    return _dataArray1.count;
    
}
#pragma mark- tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
//    if (section==0) {
//        return 0.0f;
//    }
//    else{
//        return 20.0f;
//    }
    return 10.0f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    
    switch (indexPath.row) {
            case 0:
            {
                if ([AccountTools getUserToken])
                {
                [self.navigationController pushViewController:[OrderViewController new] animated:TRUE];
                }else
                {//没有token ，进入登录界面
                    [self gotoLogin];
                }

            }
                break;
            case 1:
            {
                if ([AccountTools getUserToken])
                {
                    [self.navigationController pushViewController:[ChangePwdViewController new] animated:TRUE];
                }else
                {//没有token ，进入登录界面
                    [self gotoLogin];
                }

            }
                break;
            case 2:
            {
                [self.navigationController pushViewController:[FeedbackViewController new] animated:TRUE];

            }
                break;
                
                break;
                
            default:
                break;
        }
    
}
#pragma mark -  拍照或相册选取  0相册 1拍照
//- (void)showTheImagePickerController:(int)carmerType{
//    
//    NSUInteger sourceType;
//    if (carmerType ==1) {
//        sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
//    }else if(carmerType == 2){
//        sourceType = UIImagePickerControllerSourceTypeCamera;
//    }
//    UIImagePickerController *imgPicker = [[UIImagePickerController alloc] init];
//    imgPicker.delegate = self;
//    imgPicker.allowsEditing = YES;
//    imgPicker.sourceType = sourceType;
//    [imgPicker.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName,nil]];
//    [self presentViewController:imgPicker animated:YES completion:^{
//        // 改变状态栏的颜色  为正常  这是这个独有的地方需要处理的
//        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
//        
//    }];
//    
//}
//- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
//{
//    if ([AccountTools isLogin]== TRUE) {
//        //上传头像
//        NSString * dataStr = [AppGlobalClass PostImagesToServer:UPDATEUSERHEADPHOTO dicPostParams:(NSMutableDictionary*)@{@"token":[AccountTools getUserToken]} dicImages:(NSMutableDictionary*)@{@"HeadPhoto":image}];
//        NSDictionary *dictionary = [AppGlobalClass dictionaryWithJsonString:dataStr];
//        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
//        {
//            [[NSUserDefaults standardUserDefaults]setObject:[[[[[dictionary objectForKey:@"responseData"] firstObject]objectForKey:@"rows"] firstObject] objectForKey:@"userHeadPhoto"] forKey:@"userHeadPhoto"];
//            ALERT_VIEW(@"上传成功");
//            
//            
//            [self.headBtn setImage:image forState:UIControlStateNormal];
//        }
//        else{
//            if ([[dictionary objectForKey:@"message"] isEqualToString:@"登录失败，请重新登录"])
//            {
//                [self reloginView];//token失效的情况
//            }else
//            {
//                if ([CheckNetWork isExistenceNetwork]==FALSE) {
//                    ALERT_VIEW(@"请检查网络");
//                    
//                }
//                else{
//                    ALERT_VIEW([dictionary objectForKey:@"message"]);
//                    
//                }
//            }
//        }
// [self dismissViewControllerAnimated:YES completion:nil];
//    }
//    else
//    {
//         [self dismissViewControllerAnimated:YES completion:nil];
//        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"尚未登录，请先登录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
//        [alert show];
//    }
//    
//    
//}
//
//- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
//{
//    [self dismissViewControllerAnimated:YES completion:nil];
//}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(void)reloginView
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"账号在另一台机器登录，请重新登录!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}
#pragma mark------------alertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //删除token等用户数据
    [AccountTools exitLogin];
    LoginViewController *loginViewCon = [[LoginViewController alloc]init];
    loginViewCon.comeFromType = 1;
    [self presentViewController:loginViewCon animated:TRUE completion:^{}];
}

#pragma mark - UIScrollViewDelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    CGPoint piont = scrollView.contentOffset;
    CGRect frame = self.backColorView.frame;
    if (piont.y < 0) {
        frame.size.height = - piont.y + 5;
        self.backColorView.frame = frame;
    }else{
        frame.size.height = 5;
        self.backColorView.frame = frame;
    }
    
}

- (UIView *)backColorView{
    if (_backColorView == nil) {
        _backColorView = [[UIView alloc]initWithFrame:CGRectMake(0, 61, SCREEN_WIDTH, 5)];
        _backColorView.backgroundColor = [UIColor hexStringToColor:COLOR_VALUE];
        [self.view addSubview:_backColorView];
    }
    
    return _backColorView;
}
#pragma mark-手机号加*
-(NSString *)secureThePhoneNum:(NSString *)phoneNum
{
//    :NSMakeRange(3,4)3:location,4:length
        return [phoneNum stringByReplacingCharactersInRange:NSMakeRange(3,4) withString:@"****"];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
